package chapter_3.client;

import chapter_3.frame.DelimitFramer;
import chapter_3.frame.Framer;
import chapter_3.message.coder.BinaryMessageCoder;
import chapter_3.message.coder.MessageCoder;
import chapter_3.message.entity.AbstractMessage;
import chapter_3.message.entity.RequestMessage;
import chapter_3.message.entity.ResponseMessage;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * 创建一个TCP客户端，通过向服务器发送数据来模拟投票请求和查询请求，并从接收的数据中解析中相应的信息
 */
public class VoteTCPClient {
    public static void main(String[] args) throws IOException {
        String destAddr = "127.0.0.1";
        int destPort = 8080;
        Socket socket = new Socket(destAddr,8080);
        OutputStream output = socket.getOutputStream();
        InputStream input = socket.getInputStream();
        //创建一个消息编码器实例，messageCoder,这里使用二进制消息编码器
        MessageCoder binMessageCoder = new BinaryMessageCoder();
        //创建一个消息的成帧器，这里使用界定符成帧
        Framer delimitFramer = new DelimitFramer(input);

        //生成要发送的消息,第一次发送的是投票消息
        Integer candidateId = 101;
        AbstractMessage voteMessage = new RequestMessage(false,candidateId);
        //将消息转换为字节数组
        byte[] binaryMsg = binMessageCoder.toWire(voteMessage);
        System.out.println("-----------------开始发送投票消息-------------------");
        System.out.println("给候选人: "+candidateId+" 投票");
        //将消息划分成帧并写入output,发送到服务器端
        delimitFramer.frameMsg(binaryMsg,output);
        System.out.println("------------------消息发送结束-----------------------");
        System.out.println();

        //在发送一个查询消息
        AbstractMessage inquiryMessage = new RequestMessage(true,candidateId);
        binaryMsg = binMessageCoder.toWire(inquiryMessage);
        System.out.println("--------------------开始发送查询消息-------------------");
        System.out.println("查询候选人: "+candidateId+"的得票数");
        delimitFramer.frameMsg(binaryMsg,output);
        System.out.println("---------------------消息发送结束-----------------------");
        System.out.println();

        //接收消息
        System.out.println("---------------------开始接收消息-------------------------");
        byte[] recvByteMsg ;
        while((recvByteMsg = delimitFramer.nextMsg())!=null){
            ResponseMessage recvMessage = (ResponseMessage) binMessageCoder.fromWire(recvByteMsg);
            System.out.println("接收到的消息类型:"+(recvMessage.getInquiryFlag()?"查询响应":"投票响应"));
            System.out.println("候选人id: "+recvMessage.getCandidate().getId());
            System.out.println("候选人票数: "+recvMessage.getCandidate().getVoteNumber());
        }
        System.out.println("----------------------消息接收结束-----------------------------");
        socket.close();
    }
}
